package com.dpwgc.demo.server;

import com.alibaba.fastjson.JSONObject;
import com.dpwgc.demo.mapper.GroupMapper;
import com.dpwgc.demo.mapper.MessageMapper;
import com.dpwgc.demo.mapper.UserGroupMapper;
import com.dpwgc.demo.mapper.UserMapper;
import com.dpwgc.demo.model.Group;
import com.dpwgc.demo.model.Message;
import com.dpwgc.demo.model.User;
import com.dpwgc.demo.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 聊天室连接（监听群内聊天消息）
 */
@ServerEndpoint("/ChatLink/{groupId}/{userId}")
@Component
public class ChatLinkServer {

    private static UserMapper userMapper;
    private static UserGroupMapper userGroupMapper;
    private static MessageMapper messageMapper;
    private static GroupMapper groupMapper;
    private static DateUtil dateUtil;

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    //消息通道
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public static void sendInfo(String userId, String message){
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 建立连接成功调用
     * @param session 会话
     * @param userId 用户id
     * @param groupId 群组id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId,@PathParam(value = "groupId") String groupId){
        sessionPools.put(userId, session);//添加用户
        addOnlineCount();

        System.out.println(userId + "加入聊天室"+groupId+"|当前人数为" + onlineNum);
        try {
            //更新用户已读消息数量
            Group group = groupMapper.queryGroupById(Integer.parseInt(groupId));
            int i = userGroupMapper.updateLookNum(Integer.parseInt(userId),Integer.parseInt(groupId),group.getChatNum());
            //建立连接
            sendMessage(session, "200");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接时调用
     * @param userId 用户id
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId){
        sessionPools.remove(userId);//删除用户
        subOnlineCount();
        System.out.println(userId + "断开webSocket连接！当前人数为" + onlineNum);
    }

    @Autowired
    public void setRepository(UserMapper userMapper) {
        ChatLinkServer.userMapper = userMapper;
    }
    @Autowired
    public void setRepository(UserGroupMapper userGroupMapper) {
        ChatLinkServer.userGroupMapper = userGroupMapper;
    }
    @Autowired
    public void setRepository(MessageMapper messageMapper) {
        ChatLinkServer.messageMapper = messageMapper;
    }
    @Autowired
    public void setRepository(GroupMapper groupMapper) {
        ChatLinkServer.groupMapper=groupMapper;
    }
    @Autowired
    public void setRepository(DateUtil dateUtil) {
        ChatLinkServer.dateUtil = dateUtil;
    }

    /**
     * 收到客户端信息
     * @param message 消息
     * @param userId 用户id
     * @param groupId 群组id
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message,@PathParam(value = "userId") String userId,@PathParam(value = "groupId") String groupId) throws IOException{

        //获取用户信息
        User user = userMapper.selectById(Integer.parseInt(userId));

        //插入消息至数据库
        Message m = new Message();
        m.setStatus(1);
        m.setMessageData(message);
        m.setGroupId(Integer.parseInt(groupId));
        m.setUserId(Integer.parseInt(userId));
        m.setCreateTime(dateUtil.getDateTime());
        m.setUpdateTime(dateUtil.getDateTime());
        messageMapper.insert(m);

        //更新群组信息
        Group group = groupMapper.queryGroupById(Integer.parseInt(groupId));
        if((user.getNickname()+"："+message).length()>16){
            group.setGroupText((user.getNickname()+"："+message).substring(0, 15)+"...");
        }
        else{
            group.setGroupText(user.getNickname()+"："+message);
        }
        group.setUpdateTime(dateUtil.getDateTime());
        group.setChatNum(group.getChatNum()+1);
        int i = groupMapper.updateGroupById(group);

        //返回用户头像与昵称
        m.setHeadImg(user.getHeadImg());
        m.setNickname(user.getNickname());

        //更新用户已读消息数量
        int i1 = userGroupMapper.updateLookNum(Integer.parseInt(userId),Integer.parseInt(groupId),group.getChatNum());

        //转换为json字符串发送
        Object json = JSONObject.toJSON(m);
        message = json.toString();;

        for (Session session: sessionPools.values()) {
            try {
                //如果是群组id相同的连接
                if(session.getPathParameters().get("groupId").equals(groupId)){
                    //向其推送消息
                    sendMessage(session, message);
                }
            } catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
